﻿using Microsoft.Extensions.Logging;
using NuGet.Common;
using System.Text.Json;

namespace QuickGet.Core
{
    public class NugetLogger : NuGet.Common.ILogger
    {
        private readonly Microsoft.Extensions.Logging.ILogger _logger;

        public static Func<Dictionary<string, string?>, Exception?, string> Formatter = (state, ex) => JsonSerializer.Serialize(state);

        public NugetLogger(Microsoft.Extensions.Logging.ILogger logger)
        {
            _logger = logger;
        }

        private Microsoft.Extensions.Logging.LogLevel _map(NuGet.Common.LogLevel level)
        {
            return level switch
            {
                NuGet.Common.LogLevel.Debug => Microsoft.Extensions.Logging.LogLevel.Debug,
                NuGet.Common.LogLevel.Warning => Microsoft.Extensions.Logging.LogLevel.Warning,
                NuGet.Common.LogLevel.Information => Microsoft.Extensions.Logging.LogLevel.Information,
                NuGet.Common.LogLevel.Error => Microsoft.Extensions.Logging.LogLevel.Error,
                _ => Microsoft.Extensions.Logging.LogLevel.Trace,
            };
        }

        public void Log(NuGet.Common.LogLevel level, string data)
        {
            _logger.Log(_map(level), new Microsoft.Extensions.Logging.EventId(0, "Nuget"), data, null, (t, e) => t);
        }


        public void Log(ILogMessage message)
        {
            _logger.Log(
                _map(message.Level),
                new Microsoft.Extensions.Logging.EventId((int)message.Code, message.Code.ToString()),
                new Dictionary<string, string?>
                {
                    ["Warning"] = message.WarningLevel.ToString(),
                    ["Message"] = message.Message,
                    ["ProjectPath"] = message.ProjectPath,
                    ["Date"] = message.Time.ToString(),
                },
                null,
                Formatter);
        }

        public Task LogAsync(NuGet.Common.LogLevel level, string data)
        {
            Log(level, data);
            return Task.CompletedTask;
        }

        public Task LogAsync(ILogMessage message)
        {
            Log(message);
            return Task.CompletedTask;
        }

        public void LogDebug(string data)
        {
            _logger.LogDebug(data);
        }

        public void LogError(string data)
        {
            _logger.LogError(data);
        }

        public void LogInformation(string data)
        {
            _logger.LogInformation(data);
        }

        public void LogInformationSummary(string data)
        {
            _logger.LogInformation(data);
        }

        public void LogMinimal(string data)
        {
            _logger.LogTrace(data);
        }

        public void LogVerbose(string data)
        {
            _logger.LogTrace(data);
        }

        public void LogWarning(string data)
        {
            _logger.LogWarning(data);
        }
    }
}
